<template>
    <div class="menu-management-container">
      <div class="menu-tree">
        <MenuTree :rolePermissions="rolePermissions" @update:rolePermissions="updateRolePermissions" />
      </div>
      <div class="menu-table">
        <el-card>
          <el-form inline>
            <el-form-item label="菜单名称">
              <el-input v-model="searchName" placeholder="请输入菜单名称" @input="handleSearch" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="queryMenus">查询</el-button>
              <el-button type="success" @click="openAddDialog">新增菜单</el-button>
            </el-form-item>
          </el-form>
        </el-card>
  
        <el-table
          :data="paginatedMenus"
          stripe
          style="width: 100%; height: 630px; overflow-y: auto;"
        >
          <el-table-column prop="menu" label="是否一级菜单" />
          <el-table-column prop="submenu" label="是否二级菜单" />
          <el-table-column prop="parent" label="父菜单ID" />
          <el-table-column prop="menuindex" label="菜单编号" />
          <el-table-column prop="label" label="菜单名称" />
          <el-table-column prop="iconClass" label="图标类名" />
          <el-table-column prop="router" label="路径" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="primary" size="small" @click="openEditDialog(scope.row)">编辑</el-button>
              <el-button type="danger" size="small" @click="deleteMenu(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 20, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        />
      </div>
  
      <!-- 新增菜单对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增菜单">
      <el-form ref="addForm" :model="newMenu" :rules="rules" label-width="120px">
        <el-form-item label="是否一级菜单" prop="menu">
          <el-select v-model="newMenu.menu">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否二级菜单" prop="submenu">
          <el-select v-model="newMenu.submenu" :disabled="newMenu.menu">
            <el-option label="是" :value="true" />
            <el-option label="否" :value="false" />
          </el-select>
        </el-form-item>
        <el-form-item label="父菜单ID" prop="parent">
          <el-select v-model="newMenu.parent" :disabled="newMenu.menu" placeholder="请选择父菜单">
            <el-option
              v-for="item in parentMenus"
              :key="item.menuindex"
              :label="item.label"
              :value="item.menuindex"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单编号" prop="menuindex">
          <el-input v-model="newMenu.menuindex" />
        </el-form-item>
        <el-form-item label="菜单名称" prop="label">
          <el-input v-model="newMenu.label" />
        </el-form-item>
        <el-form-item label="图标类名" prop="iconClass">
          <el-input v-model="newMenu.iconClass" placeholder="请输入图标类名">
            <template #suffix>
              <el-button @click="openIconDialog" icon="el-icon-search" circle />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="路径" prop="router">
          <el-input v-model="newMenu.router" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addMenu">确定</el-button>
      </template>
    </el-dialog>
  
      <!-- 编辑菜单对话框 -->
      <el-dialog v-model="editDialogVisible" title="编辑菜单">
        <el-form ref="editForm" :model="editMenu" label-width="120px">
          <el-form-item label="是否一级菜单">
            <el-select v-model="editMenu.menu">
              <el-option label="是" value=true />
              <el-option label="否" value=false />
            </el-select>
          </el-form-item>
          <el-form-item label="是否二级菜单">
            <el-select v-model="editMenu.submenu">
              <el-option label="是" value=true />
              <el-option label="否" value=false />
            </el-select>
          </el-form-item>
          <el-form-item label="父菜单ID">
          <el-select v-model="editMenu.parent">
            <el-option
              v-for="item in parentMenus"
              :key="item.menuindex"
              :label="item.label"
              :value="item.menuindex"
            />
          </el-select>
        </el-form-item>
          <el-form-item label="菜单编号">
            <el-input v-model="editMenu.menuindex" />
          </el-form-item>
          <el-form-item label="菜单名称">
            <el-input v-model="editMenu.label" />
          </el-form-item>
          <el-form-item label="图标类名">
            <el-input v-model="editMenu.iconClass" placeholder="请输入图标类名">
              <template #suffix>
                <el-button @click="openIconDialog" icon="el-icon-search" circle />
              </template>
            </el-input>
          </el-form-item>
          <el-form-item label="路径">
            <el-input v-model="editMenu.router" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="updateMenu">确定</el-button>
        </template>
      </el-dialog>

      <!-- 图标选择对话框 -->
      <el-dialog v-model="iconDialogVisible" title="选择图标">
        <div class="icon-list">
          <el-icon v-for="(icon, menuindex) in elementPlusIcons" :key="menuindex" :size="20" @click="selectIcon(icon)">
            <component :is="icon" />
          </el-icon>
        </div>
      </el-dialog>
    </div>
  </template>
  
  <script lang="ts" setup>
  import { defineComponent, ref, computed, watch, onMounted } from 'vue';
  import MenuTree from './MenuTree.vue';
  import { getMenuTree,getMenu, addMenuItem, deleteMenuItem, updateMenuItem } from '../utils/menu';
  import * as ElementPlusIconsVue from '@element-plus/icons-vue';
  
   
      const treeData = ref<any[]>([]);
      const rolePermissions = ref<string[]>([]);
      const searchName = ref('');
      const currentPage = ref(1);
      const pageSize = ref(15);
      const total = ref(0);
      const addDialogVisible = ref(false);
      const editDialogVisible = ref(false);
      const iconDialogVisible = ref(false);
      const newMenu = ref<any>({
        menu: false,
        submenu: false,
        parent: '',
        menuindex: '',
        label: '',
        iconClass: '',
        router: ''
      });
      const editMenu = ref<any>({});
      const selectedMenus = ref<any[]>([]); 
      const elementPlusIcons = ref(Object.values(ElementPlusIconsVue));
  
      const paginatedMenus = computed(() => {
        const start = (currentPage.value - 1) * pageSize.value;
        const end = start + pageSize.value;
        return filteredMenus.value.slice(start, end);
      });
  
      const filteredMenus = ref<any[]>([]);

      const rules = ref({
  parent: [
    { required: true, message: '请选择父菜单', trigger: 'change' }
  ],
  label: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' }
  ],
  menuindex: [
    { required: true, message: '请输入菜单编号', trigger: 'blur' }
  ]
});

watch(() => newMenu.value.menu, (newValue) => {
  if (newValue) { // 如果选择“是”，父菜单ID应为空且禁用
    newMenu.value.parent = '';
    newMenu.value.submenu = false; // 一级菜单不能是二级菜单
  } else { // 如果选择“否”，父菜单ID应可选
    newMenu.value.submenu = true; // 默认允许选择二级菜单
  }
});

      const parentMenus = computed(() => {
        debugger;
          const parentMenus = treeData.value.filter(menu => menu.menu);
          const menu = convertStringsToBooleansAndFilterMenuTrue(parentMenus);
          return menu;
        });


        function convertStringsToBooleansAndFilterMenuTrue(data) {
              if (Array.isArray(data)) {
                  // 如果是数组，递归处理每个元素，并筛选出符合条件的对象
                  return data
                      .map(item => convertStringsToBooleansAndFilterMenuTrue(item))
                      .filter(item => item && item.menu === true); // 筛选 menu === true 的对象
              } else if (data !== null && typeof data === 'object') {
                  // 如果是对象，递归处理每个键值对
                  const result = {};
                  for (const key in data) {
                      if (data[key] === "true") {
                          result[key] = true;
                      } else if (data[key] === "false") {
                          result[key] = false;
                      } else {
                          result[key] = convertStringsToBooleansAndFilterMenuTrue(data[key]);
                      }
                  }
                  return result;
              }
              // 如果是基本类型，直接返回
           return data;
}
  
      const handleSearch = () => {
        filteredMenus.value = treeData.value.filter(menu =>
          menu.label.toLowerCase().includes(searchName.value.toLowerCase())
        );
        currentPage.value = 1;
        total.value = filteredMenus.value.length;
      };
  
      /**
       * 异步函数：查询菜单
       * 该函数用于获取菜单数据，并将其用于更新当前组件的状态
       * 它执行以下操作：
       * 1. 调用getMenu函数获取菜单数据
       * 2. 将获取到的菜单数据赋值给treeData和filteredMenus
       * 3. 更新total的值，设置为菜单数据的长度
       */
      const queryMenus = async () => {
        treeData.value = await getMenu();
        filteredMenus.value = treeData.value;
        total.value = treeData.value.length;
      };
  

      const updateRolePermissions = (newPermissions: string[]) => {
        rolePermissions.value = newPermissions;
        if (newPermissions.length === 0) {
                    queryMenus();
        } else {
            selectedMenus.value = treeData.value.filter(menu => menu.menuindex && newPermissions.includes(menu.menuindex));
            filteredMenus.value = treeData.value.filter(menu => menu.menuindex && newPermissions.includes(menu.menuindex));
        }
    };
  
      const addMenu = async () => {
        debugger;
        await addMenuItem(newMenu.value);
        addDialogVisible.value = false;
        await queryMenus(); 
      };
  
      const deleteMenu = async (Menu: any) => {
        await deleteMenuItem(Menu);
        await queryMenus(); 
      };
  
      const openAddDialog = () => {
        newMenu.value = {
          menu: false,
          submenu: false,
          parent: '',
          menuindex: '',
          label: '',
          iconClass: '',
          router: ''
        };
        addDialogVisible.value = true;
      };
  
      const openEditDialog = (menu: any) => {
        debugger 
        editMenu.value = {...menu };
        editDialogVisible.value = true;
      };
  
      const updateMenu = async () => {
        await updateMenuItem(editMenu.value);
        editDialogVisible.value = false;
        await queryMenus(); 
      };
  
      const openIconDialog = () => {
        iconDialogVisible.value = true;
      };

      const selectIcon = (icon: any) => {
        newMenu.value.iconClass = icon.name; // 假设图标组件有 name 属性，可根据实际情况修改
        editMenu.value.iconClass = icon.name;
        iconDialogVisible.value = false;
      };
  
      const handleSizeChange = (newSize: number) => {
        pageSize.value = newSize;
      };
  
      const handleCurrentChange = (newPage: number) => {
        currentPage.value = newPage;
      };
  
      onMounted(() => {
        queryMenus();
      });
   
    
  </script>
  
  <style scoped>
.menu-management-container {
    display: flex;
    justify-content: space-between;
  }
  
.menu-tree {
    width: 15%;
    height: 770px;
    overflow-y: auto;
    border-right: 1px solid #e4e7ed; /* 添加右侧分割线 */
    padding-right: 16px; /* 右侧内边距 */
    box-sizing: border-box; /* 防止内边距影响布局 */
  }

 
  
.menu-table {
    width: 85%;
    margin-left: 10px;
    
  }
.icon-list {
    display: flex;
    flex-wrap: wrap;
  }

  el-card {
  margin-bottom: 16px; /* 卡片底部外边距 */
}

.el-table {
  height: calc(100% - 120px); /* 表格高度减去搜索栏和分页高度 */
  overflow-y: auto; /* 允许垂直滚动 */
}

.el-pagination {
  margin-top: 16px; /* 分页组件顶部外边距 */
  text-align: right; /* 分页组件右对齐 */
}

.icon-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px; /* 图标之间的间距 */
  max-height: 400px; /* 图标列表最大高度 */
  overflow-y: auto; /* 允许垂直滚动 */
}

.el-icon {
  cursor: pointer; /* 鼠标悬停时显示手型 */
  padding: 8px; /* 图标内边距 */
  border: 1px solid #e4e7ed; /* 图标边框 */
  border-radius: 4px; /* 图标圆角 */
  transition: background-color 0.3s; /* 背景色过渡效果 */
}

.el-icon:hover {
  background-color: #f5f7fa; /* 鼠标悬停时背景色 */
}



  </style>